package com.zhitong.money.controller;

import com.github.pagehelper.PageInfo;
import com.zhitong.money.entity.AjaxResponse;
import com.zhitong.money.entity.CheckTime;
import com.zhitong.money.entity.Dept;
import com.zhitong.money.exception.RepeatException;
import com.zhitong.money.services.api.ICheckService;
import com.zhitong.money.services.api.IDeptService;
import com.zhitong.money.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
public class CheckContro {

    @Autowired
    private ICheckService service;

    @Autowired
    private IDeptService deptService;

    @GetMapping("/check/{id}")
    public AjaxResponse getcheckById(@PathVariable String id) throws Exception{
        CheckTime checkById = service.findCheckById(id);
        return AjaxResponse.success(checkById);
    }

    @GetMapping("/checks")
    public AjaxResponse getAllCheck() throws Exception{
        List<CheckTime> allCheckTime = service.findAllCheck();
        return AjaxResponse.success(allCheckTime);
    }

    @RequiresPermissions({"addCheck"})
    @PostMapping("/addCheck")
    public AjaxResponse addCheckByMap(@RequestBody Map<String,Object> map) throws Exception{
        service.addCheck(map);
        return AjaxResponse.success("添加成功");
    }


    @PostMapping("/checks")
    public AjaxResponse getCheckByPage(@RequestBody Map<String,Object> map) throws Exception{
        PageInfo allCheckByPage = service.findAllCheckByPage(map);
        return AjaxResponse.success(allCheckByPage);
    }

    @PostMapping("/checkMap")
    public AjaxResponse getCheckByMap(@RequestBody Map<String,Object> map) throws Exception{
        List<CheckTime> checkByMap = service.findCheckByMap(map);
        return AjaxResponse.success(checkByMap);
    }

    @RequiresPermissions({"addCheck"})
    @PostMapping("/check")
    public AjaxResponse addCheck(@RequestBody CheckTime checkTime) throws Exception{
        service.addCheck(checkTime);
        return AjaxResponse.success("考勤生成成功!");
    }

    @RequiresPermissions({"updateCheck"})
    @PutMapping("/check")
    public AjaxResponse updateCheck(@RequestBody CheckTime checkTime) throws Exception{
        service.updateCheck(checkTime);
        return AjaxResponse.success("考勤修改成功!");
    }


    @GetMapping("/signIn/{tid}")
    public AjaxResponse signIn(@PathVariable String tid) throws Exception{
        String dateTime = DateUtil.dateToStr(new Date(),DateUtil.FORMAT1);
        String[] s = dateTime.split(" ");
        Map<String,Object> map=new HashMap<>();
        map.put("date",s[0]);
        List<CheckTime> checkByMap = service.findCheckByMap(map);
        if (checkByMap.isEmpty()){
            return AjaxResponse.fail("今天不用签到!");
        }
        CheckTime checkTime = checkByMap.get(0);
        if (checkTime.getResult().equals("04")){
            return AjaxResponse.success("今天已经请假!无需签到");
        }
        //判断是否已经签到
        Instant startTime = checkTime.getStartTime();
        if (startTime!=null){
            return AjaxResponse.success("今天已签到!");
        }
        //签到
        Instant instant=DateUtil.StrToDate(s[1],DateUtil.FORMAT_DATE_Time).toInstant();
        checkTime.setStartTime(instant);
        //判断签到时间是否正常
        Dept deptByTid = deptService.findDeptByTid(tid);
        checkTime.setStatus("01");
        if (instant.getEpochSecond() <= deptByTid.getStartTime().getEpochSecond()){
            checkTime.setResult("01");
        }else{
            checkTime.setResult("00");
        }
        service.updateCheck(checkTime);
        return AjaxResponse.success("签到成功!");
    }


    @GetMapping("/signOut/{tid}")
    public AjaxResponse signOut(@PathVariable String tid) throws Exception{
        String dateTime = DateUtil.dateToStr(new Date(),DateUtil.FORMAT1);
        String[] s = dateTime.split(" ");
        Map<String,Object> map=new HashMap<>();
        map.put("date",s[0]);
        List<CheckTime> checkByMap = service.findCheckByMap(map);
        if (checkByMap.isEmpty()){
            return AjaxResponse.fail("今天不用签退!");
        }
        CheckTime checkTime = checkByMap.get(0);
        if (checkTime.getResult().equals("04")){
            return AjaxResponse.success("今天已经请假!无需签退");
        }
        //判断是否已经签到
        Instant endTime = checkTime.getEndTime();
        if (endTime!=null){
            return AjaxResponse.success("今天已签退!");
        }
        //签到
        Instant instant=DateUtil.StrToDate(s[1],DateUtil.FORMAT_DATE_Time).toInstant();
        checkTime.setEndTime(instant);
        //判断签到时间是否正常
        Dept deptByTid = deptService.findDeptByTid(tid);
        checkTime.setStatus("01");
        if (checkTime.getStartTime()==null){
            checkTime.setResult("03");
        }else{
            if (instant.getEpochSecond() >= deptByTid.getEndTime().getEpochSecond()){
                if (checkTime.getResult().equals("01")){
                    checkTime.setResult("01");
                }else{
                    checkTime.setResult("00");
                }
            }else{
                if (checkTime.getResult().equals("01")){
                    checkTime.setResult("02");
                }else{
                    checkTime.setResult("06");
                }
            }
        }
        service.updateCheck(checkTime);
        return AjaxResponse.success("签退成功!");
    }

    @RequiresPermissions({"delCheck"})
    @DeleteMapping("/check/{id}")
    public AjaxResponse delCheck(@PathVariable String id) throws Exception{
        service.delCheck(id);
        return AjaxResponse.success("考勤删除成功!");
    }

    @PostMapping("/delChecks")
    public AjaxResponse delCheckByIds(@RequestBody List<String> ids) throws Exception{
        service.delCheckByIds(ids);
        return AjaxResponse.success("考勤删除成功!");
    }

    @RequiresPermissions({"export"})
    @PostMapping("/exportChecks")
    public  void exportCheck(@RequestBody Map<String,Object> map, HttpServletResponse response) {
        try {
            service.exportChecks(map,response);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
